<?php
namespace Admin\Behaviors;

use Think\Behavior;

class CheckAuthBehavior extends Behavior
{
    public function run(&$params)
    {
        $this->checkSessionIdle();
        $this->checkAuth();
    }

    //检查是否登录超时
    public function checkSessionIdle()
    {
        $tm = NOW_TIME;
        $idle = session('idle');
        if(is_null($idle)){ $idle = 0; }
        if($tm <= $idle){
            session('idle', $tm+C('SESSION_IDLE'));
        }else{
            if(CONTROLLER_NAME !== 'Auth'){
                session(null);
            }
        }
    }

    //检查权限
    function checkAuth($noPermissionStop = true)
    {
        if(in_array(CONTROLLER_NAME, array('Auth', 'Empty'))){ return true; }
        if(strpos(ACTION_NAME, 'pass_') === 0){ return true; }
        $admin_id = is_admin_login();
        if($admin_id === 0){ redirect(U('auth/login')); } //如果没有登录，或登录超时，直接跳转
        define('ADMIN_ID', $admin_id);
        if($admin_id===1 && session('admin_name')==='root'){
            $auth = true;
        }else{
            $now = strtolower(CONTROLLER_NAME.'/'.ACTION_NAME);
            $auth = in_array($now, session('auth')) ? true : false;
        }
        if( ! $auth){
            if($noPermissionStop){
                if(IS_AJAX){
                    //如果是ajax请求
                    echo '没有权限';
                }else{
                    //正常请求，直接跳转
                    echo '<script type="text/javascript">alert("没有权限");history.go(-1);</script>';
                }
                exit;
            }
        }
        return $auth;
    }
}